<?php
/*
 * 权限组
 */
class Role extends Manager_Controller {
	function __construct(){
		parent::__construct();
	}

	function index(){
		$data['action'] = 'list';
		$this->load->model('acl/RoleModel','',true);
		$data['list'] = $this->RoleModel->selectAll();
		$this->_view('manager/acl/role',$data);
	}

	function isExistName($name) {
		$name = urldecode($name);
		$this->load->model('acl/RoleModel','',true);
		$data['state'] = $this->RoleModel->count(array('name'=>$name));
		$this->_output_json($data);
	}
	/**
	 * 新添/修改角色
	 */
	function operate ($rid=0){
		if($rid == 0){
			$data['action'] = 'add';
		}else{
			$data['action'] = 'edit';
			$this->load->model('acl/RoleModel','',true);
			$data['role'] = $this->RoleModel->selectById($rid);
		}
		$this->load->model('acl/PermissionModel','',true);
		$data['permissions'] = $this->PermissionModel->selectAlls();
		$data['message'] = $this->session->flashdata('message');
		$this->_view('manager/acl/role',$data);
	}

	/**
	 * 新添/修改角色
	 */
	function dooperate (){
		$pids = $this->input->post('pid', true ) ;
		$role = $this->input->post('role', true ) ;
		$role['pids'] = !empty($pids)?join(',',$pids):'';
		$op = 'add';
		if(isset($role['rid']) && $role['rid'] != 0){
			$op = 'edit';
		}
		$this->form_validation->set_rules($this->_setRules());
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('message','填写数据错误！');
			redirect('manager/acl/role/'.$op);
		}
		$this->load->model('acl/RoleModel','',true);
		if($op == 'edit'){
			$data['state'] = $this->RoleModel->delete($role['rid']);
		}
		if( $op == 'add' || ($op == 'edit' && $data['state']>0))
			$data['state'] = $this->RoleModel->insert($role);
		$data['message'] = '角色操作'.($data['state'] > 0?'成功。':'失败！');
		$this->_output_json($data);
	}

	/**
	 * 权限分类删除
	 */
	function dodelete ($rid=0) {
		$this->load->model('acl/UserModel','',true);
		$total = $this->UserModel->count(array('rid'=>$rid));
		$r = -1;
		if($total == 0){
			$this->load->model('acl/RoleModel','',true);
			$r = $this->RoleModel->delete($rid);
		}
//		$data['state'] = $r;
//		$data['message'] = '删除权限模块'.($r > 0?'成功。':('失败！'.$r == -1?'(模块下存在权限)':''));
		redirect('manager/acl/role');
	}
	function _setRules(){
		return array(
			array(
				"label"=>"名称",
				"field"=>"role[name]",
				"rules"=>"required"
			),
			array(
				"label"=>"排序",
				"field"=>"role[sort]",
				"rules"=>"numeric"
			)
		);
	}
}
?>